package com.hllxd.hism.star.basic.service.service;

import com.alibaba.fastjson.JSON;
import com.hllxd.hism.star.basic.service.dao.mapper.mis.RtMetricSyncConfigMapper;
import com.hllxd.hism.star.basic.service.dao.redis.ConfRedisMapper;
import com.hllxd.hism.star.basic.service.model.RtMetricSyncConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiyong.lxy
 * @date 2022.02.14
 */
@Slf4j
@Service("RtMetricSyncConfigService")
public class RtMetricSyncConfigServiceImpl implements RtMetricSyncConfigService {

    @Autowired
    private RtMetricSyncConfigMapper rtMetricSyncConfigMapper;

    @Autowired
    private ConfRedisMapper confRedisMapper;

    @Override
    public List<RtMetricSyncConfig> list() {
        return rtMetricSyncConfigMapper.listRtMetricSyncConfig();
    }

    @Override
    public Object set(RtMetricSyncConfig aa) {
        log.info("set param: {}", JSON.toJSONString(aa));
        if (aa.id == null || aa.id == 0) {
            return rtMetricSyncConfigMapper.insertRtMetricSyncConfig(aa);
        } else {
            return rtMetricSyncConfigMapper.updateRtMetricSyncConfig(aa);
        }
    }

    @Override
    public RtMetricSyncConfig get(Long id) {
        return rtMetricSyncConfigMapper.getOneRtMetricSyncConfig(id);
    }

    @Override
    public Object del(Long id) {
        return rtMetricSyncConfigMapper.updateRtMetricSyncConfigAction(id);
    }

    @Override
    public Object doEnable(Long id, Integer isEnable) {
        try {
            // 修改状态
            log.info("modify enable, id: {}, enable:{}", id, isEnable);
            rtMetricSyncConfigMapper.updateRtMetricSyncConfigEnable(id, isEnable);
        }catch (Exception e) {
            log.warn("{}, {}. Exception: {}.", id, isEnable, e.toString());
            return false;
        }

        String appId = "dapan";
        try {
            String hkey = id.toString();
            if(isEnable==0) {
                log.info("redis will del key: {}, {}.", appId, hkey);
                confRedisMapper.delItem(appId, hkey);
            }else {
                log.info("redis will add key: {}, {}.", appId, hkey);
                RtMetricSyncConfig entity = rtMetricSyncConfigMapper.getOneRtMetricSyncConfig(id);
                if (entity == null) {
                    return false;
                }
                String value = JSON.toJSONString(entity);
                confRedisMapper.setItem(appId, hkey, value);
            }
        } catch (Exception e) {
            log.warn("{}, {}.Exception: {}", id, isEnable, e.toString());
            return false;
        }
        return true;
    }
}
